package com.example.student.service.Impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.constants.RdsConstants;
import com.example.common.domain.pojo.Experiment;
import com.example.common.utils.CacheClient;
import com.example.student.mapper.ExperimentMapper;
import com.example.student.service.ExperimentService;
import jakarta.persistence.EntityNotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class ExperimentServiceImpl extends ServiceImpl<ExperimentMapper, Experiment> implements ExperimentService {

    @Autowired
    private ExperimentMapper experimentMapper;
    @Autowired
    private CacheClient cacheClient;


    @Override
    public Experiment getExperimentById(String id) {
        // 使用逻辑过期策略获取
        return cacheClient.queryWithLogicalExpire(
                RdsConstants.EXPERIMENT_INFO,
                id,
                Experiment.class,
                this::getById, // 使用MyBatis-Plus的基础方法
                RdsConstants.CACHE_NULL_TTL,
                TimeUnit.MINUTES,
                false
        );
    }

    @Override
    public void saveExperiment(Experiment experiment) {
        experimentMapper.insert(experiment);
    }

    @Override
    public void updateExperiment(Experiment experiment) {
        // 参数校验：确保主键存在
        if (experiment.getId() == null) {
            log.warn("更新实验时必须提供id");
            throw new IllegalArgumentException("更新实验时必须提供id");
        }
        // 构建UpdateWrapper
        UpdateWrapper<Experiment> updateWrapper = new UpdateWrapper<>();

        // 设置更新条件（主键）
        updateWrapper.lambda()
                .eq(Experiment::getId, experiment.getId());

        // 动态设置需要更新的字段（只更新非null值）
        LambdaUpdateWrapper<Experiment> lambdaUpdate = updateWrapper.lambda();

        // 基础字段更新
        if (experiment.getExperimentalContent() != null) {
            lambdaUpdate.set(Experiment::getExperimentalContent, experiment.getExperimentalContent());
        }
        if (experiment.getExperimentalFilePath() != null) {
            lambdaUpdate.set(Experiment::getExperimentalFilePath, experiment.getExperimentalFilePath());
        }
        // 状态字段更新
        if (experiment.getStatus() != null) {
            lambdaUpdate.set(Experiment::getStatus, experiment.getStatus());
        }
        // 时间字段更新
        if (experiment.getStartTime() != null) {
            lambdaUpdate.set(Experiment::getStartTime, experiment.getStartTime());
        }
        if (experiment.getEndTime() != null) {
            lambdaUpdate.set(Experiment::getEndTime, experiment.getEndTime());
        }
        // 自动填充更新时间（如果实体类未通过注解自动处理）
        lambdaUpdate.set(Experiment::getEndTime, new Timestamp(System.currentTimeMillis()));
        // 执行更新操作
        int rows = experimentMapper.update(null, updateWrapper);
        // 检查更新结果
        if (rows == 0) {
            log.warn("更新实验失败，未找到记录，id={}");
            throw new EntityNotFoundException("未找到对应实验记录，id=" + experiment.getId());
        }
    }


}
